import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_picker/Picker.dart';

class DateTimePicker extends StatelessWidget {

  final int day;
  final Function(List list) onSelect;

  const DateTimePicker({Key key, this.day, this.onSelect}) : super(key: key);

  //时间选择器内容选择    [day] 时间选择区间默认31天
  List getTime({int day = 31}) {
    var now = DateTime.now();
    List<Map<String, List<Map<String, List>>>> list = [];
    for (int i = 0; i < day; i++) {
      if (list.length > 0) {
        //判断年是否存在
        bool year = false;
        int yearIndex = 0;
        for (int j = 0; j < list.length; j++) {
          year = list[j].keys.toList()[0] == '${now.year}年';
          if (year) {
            yearIndex = j;
            break;
          }
        }
        if (year) {
          bool month = false;
          int monthIndex = 0;
          for (int j = 0; j < list[yearIndex]['${now.year}年'].length; j++) {
            //判断月份是否存在
            month = list[yearIndex]['${now.year}年'][j].keys.toList()[0] ==
                '${now.month}月';
            if (month) {
              monthIndex = j;
              break;
            }
          }
          if (month) {
            list[yearIndex]['${now.year}年'][monthIndex]['${now.month}月'].add({
              '${now.day}日': ['7:00-12:00', '13:00-19:00']
            });
          } else {
            list[yearIndex]['${now.year}年'].add({
              '${now.month}月': [
                {
                  '${now.day}日': ['7:00-12:00', '13:00-19:00']
                },
              ]
            });
          }
        } else {
          list.add({
            '${now.year}年': [
              {
                '${now.month}月': [
                  {
                    '${now.day}日': ['7:00-12:00', '13:00-19:00']
                  },
                ]
              }
            ]
          });
        }
      } else {
        list.add({
          '${now.year}年': [
            {
              '${now.month}月': [
                {
                  '${now.day}日': ['7:00-12:00', '13:00-19:00']
                },
              ]
            }
          ]
        });
      }
      now = now.add(Duration(days: 1));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: JsonDecoder().convert(jsonEncode(getTime()))),
        changeToFirst: false,
        textAlign: TextAlign.left,
        textStyle: const TextStyle(color: Colors.blue),
        selectedTextStyle: TextStyle(color: Colors.red),
        columnPadding: const EdgeInsets.all(8.0),
        onConfirm: (Picker picker, List value) {
          var data = picker.getSelectedValues();
          if(onSelect!=null)onSelect.call(data);
        }).makePicker();
  }
}
